<?php
/**
 * Created by PhpStorm.
 * User: 86188
 * Date: 2022/3/19
 * Time: 21:34
 */

namespace app\applet\controller;


use app\BaseController;
use app\service\BillService;
use app\Service\communityService;
use app\Service\WechatService;
use think\facade\Db;

class Bill extends BaseController
{
    //根据房屋id获取未支付账单信息
    public function unPayListByRoomId(){

        //根据小区和完整门牌号查询房屋信息
        $room_id=request()->param("room_id");
        //$room_id="107168";
        $roominfo = Db::table("roominfo")->where("id",$room_id)->find();

        if(empty($roominfo)){
            parent::sendOutput("房屋信息不存在",500);
        }
        //Log::write($roominfo,"122");
        //根据房号查询账单

        $billlis = (new BillService())->billRoomIdList($roominfo["community_id"],$roominfo["out_room_id"]);
        if(empty($billlis)){
            parent::sendOutput("暂无可缴费账单",500);
        }
        $costTypes = (new BillService())->cost_type($roominfo["community_id"],$roominfo["out_room_id"]);
        $costTypeMaps=Db::table("costtype")->select();
        $maps=[];
        foreach ($costTypeMaps as $value){
            $maps[$value["type"]]=$value["cost_name"];
        }
        $lis=[];
        $sumMoney=0;
        $billIds=[];
        $selectBill=[];
        foreach ($costTypes as $b){
            $item=[];
            $item["cost_type"]=$b;
            $item["cost_type_name"]=isset($maps[$b])?$maps[$b]:'';
            $bill = (new BillService())->cost_type_bill($roominfo["community_id"],$roominfo["out_room_id"],$b);
            $arr=[];
            foreach ($bill as &$value){
                $value["cost_type"]=isset($maps[$value["cost_type"]])?$maps[$value["cost_type"]]:'';
                $value["owner_name"]=$roominfo["owner_name"];
                $value["selected"]=true;
                $arr[]=$value;
                $sumMoney+=$value["bill_entry_amount"];
                $billIds[]=$value["id"];
                $selectBill[]=$value;
            }
            $item["bill"]=$arr;
            $lis[]=$item;
        }
        if(empty($lis)){
            parent::sendOutput("暂无可缴费账单",500);
        }
        $data["roomBillDetail"]=$lis;
        $data["room"]=$roominfo;
        $data["sumMoney"]=$sumMoney;
        $data["maps"]=$maps;
        $data["billIds"]= $billIds;
        $data["selectBill"]= $selectBill;
        parent::sendOutput($data);

    }

    //计算要缴费的金额
    public function moneySum(){
        $post=request()->post();
        $orderMoney=0;
        if(!(request()->has('billId'))){
            parent::sendOutput("账单不能为空",500);
            return json(['state'=>'1','info' => "0"]);
        }
        foreach ($post["billId"] as $key => $value) {
            $billinfo=Db::table("bill")->where('id',$value)->find();
            //parent::sendOutput($billinfo);
            $orderMoney=$orderMoney+$billinfo["bill_amount"];
        }
        $data["order_money"]=$orderMoney;


        $data["pay_money"]=round($data["order_money"],2);
        parent::sendOutput($data);
    }
    public function orderPay(){
        if(!(request()->has('billid'))){
            return json_encode(['info' => '请选择要交费的账单']);
        }

        $post=request()->post();
        //校验参数与订单金额
        $billpay["billid"]=serialize($post["billid"]);
        //Log::info('payInfo:',$post);
        $ordermoney=0;
        $subjectremark="";
        $roominfo=DB::table("roominfo")->where('id',$post["room_id"])->find();
        $out_room_id=$roominfo["out_room_id"];
        $community_id=$roominfo["community_id"];
        $room_address=$roominfo["address"];
        $communityinfo = (new communityService())->communityInfo($community_id);
        $community_name=$communityinfo["community_name"];
        foreach ($post["billid"] as $key => $value) {
            $billinfo=DB::table("bill")->where('id',$value)->find();
            if($billinfo['status']=="FINISH_PAY"){
                parent::sendOutput("该账单已缴费",500);
                return json_encode(['info' => '该帐单已缴费']);
            }
            $ordermoney=bcadd($ordermoney,$billinfo["bill_amount"],2);
            //$ordermoney=$ordermoney+$billinfo->bill_amount;

            $costtype=(new billService())->costTypeName($billinfo["cost_type"]);
            $subjectremark=$subjectremark.$costtype.":".$billinfo["bill_amount"]."元| ";
        }
        if($ordermoney!=$post["amount"]){
            parent::sendOutput("账单金额错误",500);
            return json_encode(['info' => '该账单金额错误',"ordermoney"=>$ordermoney]);
        }
        $billpay["order_money"]=$ordermoney;
        $billpay["user_id"]=$this->request->openid;;

        $billpay["out_room_id"]=$out_room_id;
        $billpay["room_address"]=$room_address;
        $billpay["community_id"]=$community_id;
        $billpay["community_name"]=$community_name;

        $billpay["pay_money"]=round($billpay["order_money"],2);
        $billpay["out_trade_no"]=date('YmdHiss').rand(100000,999999);


        $billpay["subject"]=$subjectremark;
        //生成订单
        $data['appid'] = "wx3fd7e9c4152f4823";//公众账号ID
        $data['mch_id'] ="1484539292";//

        $data['sub_appid'] = "wx6e64e3c7372be385";//公众账号ID

        $data['sub_openid']=$this->request->openid;;


        $data['sub_mch_id'] =$communityinfo["sub_mch_id"];
        $data['sub_mch_id'] ="1521888701";//    1549291381
        $data['nonce_str'] = (new WechatService())->createNoncestr();//随机字符串
        $data['body'] = $subjectremark;//商品描述
        $data['out_trade_no'] = $billpay["out_trade_no"];//商户订单号
        $data['total_fee'] = $billpay["pay_money"]*100;//总金额
        //$data['total_fee']=1;
        $data['spbill_create_ip'] = $_SERVER["REMOTE_ADDR"];//终端IP
        $data['notify_url'] = 'https://www.wyjf.zfbzhsq.com/notice/wxnotice';//通知url
        $data['trade_type'] = 'JSAPI';
        //$data['openid'] = $post["user_id"];//用户标识

        $wxkey="asdfaASDFASDFASFasfsadf6546A84SA";

        $data['sign'] = (new WechatService())->MakeSign($data,$wxkey);//签名
        // return json(['info' => $data]);
        //输出xml字符

        $xml = (new WechatService())->ToXml($data);

        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
        $payInfo = (new wechatService())->post_curl_data($url,$xml);

        $payInfo = json_decode(json_encode(simplexml_load_string($payInfo, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        //header("Content-type:text/html;charset=utf8");

        if($payInfo['return_code'] !== 'SUCCESS'){
            parent::sendOutput($payInfo['return_msg'],501);
            return json_encode(['info' => $payInfo['return_msg']]);

        }else{
            if($payInfo['result_code'] !== 'SUCCESS'){
                parent::sendOutput($payInfo['err_code_des'],501);
                return json_encode(['info' => $payInfo['err_code_des']]);
            }
            $billpay["user_id"]=$payInfo['return_msg'];
            $billpay["scenes"]=1;
            $info['trade_no'] =  $billpay["out_trade_no"];

            $res=Db::table("billpay")->insert($billpay);

            if($res){
                $jsApiParameters['appId'] = $payInfo['sub_appid'];
                $jsApiParameters['timeStamp'] = time();

                //$jsApiParameters['timeStamp'] = '$jsApiParameters["timeStamp"]';
                $jsApiParameters['nonceStr'] = (new WechatService())->createNoncestr();
                $jsApiParameters['package'] = 'prepay_id='.$payInfo['prepay_id'];
                $jsApiParameters['signType'] = 'MD5';

                $jsApiParameters['paySign'] = (new WechatService())->MakeSigns($jsApiParameters,$wxkey);

                parent::sendOutput($jsApiParameters);
                return  json_encode($jsApiParameters);
            }else{
                return json_encode(['info' => '订单存储失败']);
            }
        }
    }
    public function orderpay2(){
        $data=request()->post();
        return json_encode($data);
        $user_id =  $data['user_id'];
        $id = $data['id'];

        if(empty($id)){
            return json_encode(['errorCode'=>'1','error' => '请选择要缴费的账单']);
        }
        //根据账单编号查询账单金额
        $infolist = (new billService())->billEntryIdInfo($id);
        if(count($infolist) != count($id)){
            return json_encode(['errorCode'=>'1','info' => '账单信息不完整']);
        }
        $out_room_id="";
        $room_address="";
        $community_id="";
        $community_name="";
        $bill_entry_amount=[];
        foreach($infolist as $info){
            //查询小区名称
            $communityInfo = (new communityService())->communityInfo($info->community_id);
            $community_name=$communityInfo->community_name;
            $bill_entry_amount[] = $info->bill_amount;
            $out_room_id = $info->out_room_id;
            $community_id = $info->community_id;
            $room_address = $info->room_address;
        }

        $out_trade_no = time().rand(100000,999999);
        $bill_amount_sum = array_sum($bill_entry_amount);

        $roominfo=DB::table("roominfo")->where("out_room_id",$out_room_id)->get()->first();
        $subject = $community_name.$room_address.'-'.$roominfo->owner_name.'物业缴费';

        //查询token
        $token = (new billService())->token($community_id);
        //Log::write($token,"token");
        $api = new apiService();

        $notifyUrl="https://www.wyjf.zfbzhsq.com/notice/communitycashier/alinotice";
        $result = $api->orderCreate(json_encode(['out_trade_no'=> $out_trade_no,'total_amount'=>$bill_amount_sum,'buyer_id'=>$user_id,'subject' =>$subject,'token'=>$token ,'notifyurl'=>$notifyUrl]));

        if(property_exists($result,'sub_msg')){
            return json_encode(['errorCode'=>'1','info' => $result->sub_msg]);
        }else{
            $close_id = $id['0'];
            $is_trade_no = DB::Table('bill')->where('id',$close_id)->value('trade_no');
            if(!empty($is_trade_no)){

                $aaa = $api->close(json_encode(['trade_no' => $is_trade_no,'token' => $token]));
                if(property_exists($aaa,'sub_msg')){
                    Log::info($aaa->sub_msg);
                }
            }
            //添加进数据库
            $bill['trade_no'] =  $result->trade_no;
            $bill['out_trade_no'] = $out_trade_no;
            $bill['user_id'] = $user_id;
            foreach($id as $billid){
                //$bill['id'] = $billid;
                $billedit = (new billService())->billEdit($bill,$billid);
                if(empty($billedit)){
                    return json_encode(['errorCode'=>'1','info' => '账单存储失败']);
                }
            }
            $billpay["user_id"]=$user_id;
            $billpay["order_money"]=$bill_amount_sum;
            $billpay["pay_money"]=$bill_amount_sum;
            $billpay["out_trade_no"]= $out_trade_no;
            $billpay["trade_no"]= $bill['trade_no'];
            $billpay["billid"]=serialize($id);
            $billpay["out_room_id"]=$out_room_id;
            $billpay["room_address"]=$room_address;
            $billpay["community_name"]=$community_name;
            $billpay["community_id"]=$community_id;
            $billpay["scenes"]=2;
            $res=Db::table("billpay")->insert($billpay);
            if($res){
                $jsApiParameters['appId'] = $payInfo['sub_appid'];//小程序appid
                $jsApiParameters['timeStamp'] = time();
                // $jsApiParameters['nonceStr'] = $payInfo['nonce_str'];
                $jsApiParameters['nonceStr'] = (new wechatService())->createNoncestr();
                $jsApiParameters['package'] = 'prepay_id='.$payInfo['prepay_id'];
                $jsApiParameters['signType'] = 'MD5';
                // $jsApiParameters['paySign'] = $payInfo['sign'];
                $jsApiParameters['paySign'] = (new wechatService())->MakeSigns($jsApiParameters,$wxkey);
                $jsApiParameters['trade_no']=$order['trade_no'];
                return json_encode($jsApiParameters);
            }else{
                return json_encode(['errorCode'=>'1','info' => '账单存储失败']);
            }
        }
    }
}